package com.ykdl.member.kid.person;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.ykdl.member.kid.R;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.http.Network;
import com.ykdl.member.kid.beans.ActorDialogueBean;
import com.ykdl.member.kid.beans.BabyProfileBean;
import com.ykdl.member.kid.beans.DialoguesMessageBean;
import com.ykdl.member.kid.beans.DiaryBean;
import com.ykdl.member.kid.beans.FavoriteBean;
import com.ykdl.member.kid.beans.PersonBean;
import com.ykdl.member.kid.beans.PostBean;
import com.ykdl.member.kid.beans.ProfileBean;
import com.ykdl.member.kid.beans.RegisterPhonebean;
import com.ykdl.member.kid.beans.StatuResult;
import com.ykdl.member.kid.beans.TopicBean;
import com.ykdl.member.kid.beans.UserBean;
import com.ykdl.member.kid.circle.LookImageActivity;
import com.ykdl.member.kid.fittool.BaseActivity;
import com.ykdl.member.kid.marketcard.CardPersonalInformationActivity;
import com.ykdl.member.kid.messagebox.ChatLetterActivity;
import com.ykdl.member.kid.messagebox.FansActivity;
import com.ykdl.member.kid.models.FileMetas;
import com.ykdl.member.kid.regandlogin.RegAndLoginActivity;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.DateUtil;

public class PersonCenterActivity extends BaseActivity implements OnClickListener{
	
	private static final String TAG = PersonCenterActivity.class.getSimpleName();
	private ProgressDialog mProgressDialog;
	
	private TextView mTxtVisit;
	private TextView mTxtNickName, mTxtAge, mTxtArea, mTxtCoin, mTxtSignature, mTxtAttention, mTxtFans;
	private ImageView mImgSex, mImgAttention, mImgBabySex;
	private ImageView mImgHead;
	private TextView mTxtGrade;
	
	private TextView mTxtDiary;
	private ImageView mImgDiary1, mImgDiary2, mImgDiary3;
	
	private View mLayerFavorite;
	
	private TextView mTxtFavorite, mTxtFavoriteItme, mTxtFavoriteCircle, mTxtFavoriteDate, mTxtFavoriteReply;
	private TextView mTxtTopic, mTxtTopicItem, mTxtTopicCircle, mTxtTopicDate, mTxtTopicReply;
	private TextView mTxtReply, mTxtReplyItme, mTxtReplyCircle, mTxtReplyDate, mTxtReplyCount;
	
	private SimpleDateFormat format = new SimpleDateFormat("MM月dd日");
	
	public static final String STR_ACTOR_ID = "actor_id";
	private int actor_id;
	private int relation;
	private int mCurrentId;
	
	private BitmapUtils mBmpUtils;
	private PersonBean pb ;
	private AccessTokenKeeper mTokenKeeper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_person_center);
		Intent intent = getIntent();
		mTokenKeeper = new AccessTokenKeeper(this);
		actor_id = intent.getIntExtra(STR_ACTOR_ID, 0);
		if (actor_id != 0) {
			boolean isAnonymous = mTokenKeeper.getmisAnonymous();
			if (isAnonymous) {
				
			} else {
				RegisterPhonebean bean = AccessTokenKeeper.readAccessToken(this);
				if (!TextUtils.isEmpty(bean.getActor_id()) && actor_id  == Integer.parseInt(bean.getActor_id())) {
					actor_id = 0;
				}
			}
		} 
		mBmpUtils = new BitmapUtils(this);
		initView();
		//mProgressDialog = ProgressDialog.show(this, null, getString(R.string.loading_data), true, true);
		//Network.getInstance().requestPerson(new PersonBeanTag(), actor_id);
	}
	boolean isRefresh = true;
	@Override
	protected void onResume() {
		super.onResume();
		if (isRefresh) {
			mProgressDialog = ProgressDialog.show(this, null, getString(R.string.loading_data), true, true);
			Network.getInstance().requestPerson(new PersonBeanTag(), actor_id);
		}else {
			isRefresh = true;
		}
	}
	
	private void initView(){
		mTxtVisit = (TextView) findViewById(R.id.txtVistor);
		
		findViewById(R.id.btnBack).setOnClickListener(this);
		
		mTxtNickName = (TextView) findViewById(R.id.txtNickName);
		mImgSex = (ImageView) findViewById(R.id.imgSex);
		mImgBabySex = (ImageView) findViewById(R.id.imgBabySex);
		mTxtGrade = (TextView) findViewById(R.id.txtGrade);
		
		mImgAttention = (ImageView) findViewById(R.id.imgAttention);
		if (actor_id != 0) {
			//mImgAttention.setImageResource(R.drawable.icon_attention_me);
		} else {
			mImgAttention.setVisibility(View.GONE);
		}
		mImgAttention.setOnClickListener(this);
		
		mImgHead = (ImageView) findViewById(R.id.imgHead);
		mImgHead.setOnClickListener(this);
		mTxtAge = (TextView) findViewById(R.id.txtAge);
		mTxtArea = (TextView) findViewById(R.id.txtArea);
		mTxtCoin = (TextView) findViewById(R.id.txtCoin);
		mTxtSignature = (TextView) findViewById(R.id.txtSignature);
		mTxtAttention = (TextView) findViewById(R.id.txtAttention);
		mTxtFans = (TextView) findViewById(R.id.txtFans);
		
		if (actor_id == 0) {
			findViewById(R.id.layerEdit).setOnClickListener(this);
		} else {
			findViewById(R.id.layerEdit).setVisibility(View.GONE);
			View sendView = findViewById(R.id.layerSendmsg);
			sendView.setVisibility(View.VISIBLE);
			sendView.setOnClickListener(this);
		}
		
		findViewById(R.id.layerAttention).setOnClickListener(this);
		findViewById(R.id.layerFans).setOnClickListener(this);
		
		findViewById(R.id.layerAngleDiary).setOnClickListener(this);
		mTxtDiary = (TextView) findViewById(R.id.txtDiary);
		mImgDiary1 = (ImageView) findViewById(R.id.imgDiary1);
		mImgDiary2 = (ImageView) findViewById(R.id.imgDiary2);
		mImgDiary3 = (ImageView) findViewById(R.id.imgDiary3);
		
		mLayerFavorite = findViewById(R.id.layerFavorite);
		mLayerFavorite.setOnClickListener(this);
		mTxtFavorite = (TextView) findViewById(R.id.txtFavorite);
		mTxtFavoriteItme = (TextView) findViewById(R.id.txtFavoriteItem);
		mTxtFavoriteCircle = (TextView) findViewById(R.id.txtFavoriteCircle);
		mTxtFavoriteDate = (TextView) findViewById(R.id.txtFavoriteDate);
		mTxtFavoriteReply = (TextView) findViewById(R.id.txtFavoriteReplyCount);
				
		
		findViewById(R.id.layerTopic).setOnClickListener(this);
		mTxtTopic = (TextView) findViewById(R.id.txtTopic);
		mTxtTopicItem = (TextView) findViewById(R.id.txtTopicItem);
		mTxtTopicCircle = (TextView) findViewById(R.id.txtTopicCircle);
		mTxtTopicDate = (TextView) findViewById(R.id.txtTopicDate);
		mTxtTopicReply = (TextView) findViewById(R.id.txtTopicReplyCount);
		
		findViewById(R.id.layerReply).setOnClickListener(this);
		mTxtReply = (TextView) findViewById(R.id.txtReply);
		mTxtReplyItme = (TextView) findViewById(R.id.txtReplyItem);
		mTxtReplyCircle = (TextView) findViewById(R.id.txtReplyCircle);
		mTxtReplyDate = (TextView) findViewById(R.id.txtReplyDate);
		mTxtReplyCount = (TextView) findViewById(R.id.txtReplyCount);
		
	}
	
	private void fillData(PersonBean pb) {
		if (pb != null) {
			if (pb.getActor() != null) {
				UserBean user = pb.getActor();
				mCurrentId = user.getActor_id();
				ProfileBean profile = user.getProfile();
				
				mTxtVisit.setText(getString(R.string.vistor, pb.getVisit_count()));
				
				mTxtGrade.setText(String.valueOf(user.getLevel()));
				
				mTxtNickName.setText(user.getDisplay_name());
				//if (user.getGender() == 1) {
				//	mImgSex.setImageResource(R.drawable.icon_male);
				//} else {
				//	mImgSex.setImageResource(R.drawable.icon_female);
				//}
				mTxtAttention.setText(String.valueOf(pb.getFriends_count()));
				mTxtFans.setText(String.valueOf(pb.getFans_count()));
				//关注状态 为关注，双向关注，我关注TA,TA关注我 TODO
				relation = user.getRelation();
				if (actor_id == 0) {
					mImgAttention.setVisibility(View.INVISIBLE);
				} else {
					if (relation == UserBean.RELATION_NONE) {
						mImgAttention.setImageResource(R.drawable.icon_attention);
					} else if (relation == UserBean.RELATION_FOLLOWED_BY) {
						mImgAttention.setImageResource(R.drawable.icon_attention_ta);
					} else if (relation == UserBean.RELATION_FOLLOWING) {
						mImgAttention.setImageResource(R.drawable.icon_attentioned);
					} else if (relation == UserBean.RELATION_FRIENDS) {
						mImgAttention.setImageResource(R.drawable.icon_attentioned);
					}
				}
				
				if (user.getAvatar_file_meta() != null && user.getAvatar_file_meta().getDownload_urls() != null &&
						user.getAvatar_file_meta().getDownload_urls().getMiddle() != null &&
						!TextUtils.isEmpty(user.getAvatar_file_meta().getDownload_urls().getMiddle().getUrl())) {
					FileMetas avatar = user.getAvatar_file_meta();
					mBmpUtils.display(mImgHead, avatar.getDownload_urls().getSmal().getUrl());
					mImgHead.setTag(avatar);
				}
				
				BabyProfileBean babyProfile = user.getBaby_profile();
				if (babyProfile != null) {
					String strAge = DateUtil.getBabyAge((long) babyProfile.getBirthday()*1000, System.currentTimeMillis());
					mTxtAge.setText(strAge);
					if (babyProfile.getGender() == 1) {
						mImgBabySex.setImageResource(R.drawable.icon_baby_male);
					} else {
						mImgBabySex.setImageResource(R.drawable.icon_baby_female);
					}
				}
				
				
				//TODO 辣豆
				mTxtCoin.setText(pb.getActor()==null?"":String.valueOf(pb.getActor().getTotal_gold()));
				
				if (profile != null) {
					mTxtArea.setText(profile.getRegion());
					mTxtSignature.setText(profile.getSignature());
					if ("1".equals(profile.getGender())) {
						mImgSex.setImageResource(R.drawable.icon_male);
					} else {
						mImgSex.setImageResource(R.drawable.icon_female);
					}
				}
			}
			
			mTxtDiary.setText(getString(R.string.angel_diary, pb.getDiaries_count()));
			
			//设置图片
			ArrayList<DiaryBean> diaries = pb.getDiaries();
			if (diaries != null && diaries.size() > 0) {
				for (int i = 0; i < pb.getDiaries().size(); i++) {
					DiaryBean d = pb.getDiaries().get(i);
					if (i == 0) {
						mBmpUtils.display(mImgDiary1, d.getFile_metas().get(0).getDownload_urls().getSmal().getUrl());
					} else if (i == 1) {
						mBmpUtils.display(mImgDiary2, d.getFile_metas().get(0).getDownload_urls().getSmal().getUrl());
					} else if (i == 2) {
						mBmpUtils.display(mImgDiary3, d.getFile_metas().get(0).getDownload_urls().getSmal().getUrl());
					}
				}
			} else {
				mImgDiary1.setVisibility(View.VISIBLE);
				mImgDiary2.setVisibility(View.INVISIBLE);
				mImgDiary3.setVisibility(View.INVISIBLE);
			}
			
			if (actor_id != 0) {
				mLayerFavorite.setVisibility(View.GONE);
			} else {
				mTxtFavorite.setText(getString(R.string.favorite_shu, pb.getFavorites_count()));
				if (pb.getFavorites() != null && pb.getFavorites().size() != 0) {
					FavoriteBean fa = pb.getFavorites().get(0);
					TopicBean topic = fa.getTopic();
					if (topic != null) {
						mTxtFavoriteItme.setText(topic.getTitle());
						mTxtFavoriteReply.setText(fa.getTopic().getReply_count());
					}
					mTxtFavoriteCircle.setText(fa.getGroup()==null? "":fa.getGroup().getGroup_name());
					float time = Float.valueOf(fa.getTopic()==null? "0":fa.getTopic().getPost_time())*1000;
					String str = format.format(new Date((long)time));
					mTxtFavoriteDate.setText(str);
				}
			}
			
			mTxtTopic.setText(getString(R.string.topic, pb.getTopics_count()));
			if (pb.getTopics() != null && pb.getTopics().size() != 0) {
				TopicBean topic = pb.getTopics().get(0);
				mTxtTopicItem.setText(topic.getTitle());
				//TODO 当前帖子所在的圈子
				if (null!=topic.getGroup()) {
					mTxtTopicCircle.setText(topic.getGroup().getGroup_name());
				}
				float time = Float.valueOf(topic==null?"0":topic.getPost_time())*1000;
				mTxtTopicDate.setText(format.format(new Date((long)time)));
				mTxtTopicReply.setText(topic.getReply_count());
			}
			
			mTxtReply.setText(getString(R.string.reply, pb.getPosts_count()));
			if (pb.getPosts() != null && pb.getPosts().size() != 0) {
				PostBean post = pb.getPosts().get(0);
				mTxtReplyItme.setText(post.getMessage());
				mTxtReplyCircle.setText(post.getGroup().getGroup_name());//TODO 圈子名称
				float time = Float.valueOf(post==null?0:post.getPost_time())*1000;
				mTxtReplyDate.setText(format.format(new Date((long)time)));
				mTxtReplyCount.setText(String.valueOf(post.getLikes_count()));
			}
			
			
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.imgHead:
			if (v.getTag() != null && v.getTag() instanceof FileMetas) {
				List<FileMetas> list = new ArrayList<FileMetas>();
				list.add((FileMetas) v.getTag());
				intent = new Intent(this, LookImageActivity.class);
				intent.putExtra("list", (Serializable)list);
				startActivity(intent);
				isRefresh = false;
			}
			break;
		case R.id.imgAttention:
			if (actor_id != 0) {
				boolean isAnonymous = mTokenKeeper.getmisAnonymous();
				if (isAnonymous) {
					intent = new Intent(this, RegAndLoginActivity.class);
					intent.putExtra(KidAction.FROM, "");
					startActivity(intent);
					return;
				}
				if (relation == UserBean.RELATION_NONE ) {
					mProgressDialog = ProgressDialog.show(this, null, "发送关注中...");
					Network.getInstance().addAttention(actor_id, new AttentionTag());
				} else if (relation == UserBean.RELATION_FRIENDS || relation == UserBean.RELATION_FOLLOWING) {
					mProgressDialog = ProgressDialog.show(this, null, "发送取消关注中...");
					Network.getInstance().delAttention(actor_id, new DelAttenTag());
				}
				
			}
			break;
		case R.id.btnBack:
			finish();
			break;
		case R.id.layerEdit:
			intent = new Intent(this, CardPersonalInformationActivity.class);
			startActivity(intent);
			break;
		case R.id.layerSendmsg:
			if (actor_id != 0) {
				boolean isAnonymous = mTokenKeeper.getmisAnonymous();
				if (isAnonymous) {
					intent = new Intent(this, RegAndLoginActivity.class);
					intent.putExtra(KidAction.FROM, "");
					startActivity(intent);
				} else {
					mProgressDialog = ProgressDialog.show(this, null, "发送连接中...");
					Network.getInstance().dialogueMessage(actor_id, new DialogueTag());
				}
			}
			break;
		case R.id.layerAttention:
			intent = new Intent(this, AttentionActivity.class);
			intent.putExtra("actor_id", actor_id);
			startActivity(intent);
			break;
		case R.id.layerFans:
			intent = new Intent(this, FansActivity.class);
			intent.putExtra("actor_id", actor_id);
			startActivity(intent);
			break;
		case R.id.layerAngleDiary:
			boolean self = true;
			if (actor_id != 0) {
				self = false;
			}
			intent = new Intent(this, AngleDiaryActivity.class);
			intent.putExtra("actor_id", actor_id);
			startActivity(intent);
			break;
		case R.id.layerFavorite:
			if (pb==null || String.valueOf(pb.getFavorites_count()).equals("0")) {
				return;
			}
			intent = new Intent(this, FavoriteActivity.class);
			startActivity(intent);
			break;
		case R.id.layerTopic:  
			if (pb==null || String.valueOf(pb.getTopics_count()).equals("0")) {
				return;
			}
			if (mCurrentId==0) {
				return;
			}
			intent = new Intent(this, TopicListActivity.class);
			intent.putExtra("post_actor_id", mCurrentId);
			startActivity(intent);
			break;
		case R.id.layerReply:
			if (pb==null || String.valueOf(pb.getPosts_count()).equals("0")) {
				return;
			}
			if (mCurrentId==0) {
				return;
			}
			intent = new Intent(this, PostListActivity.class);
			intent.putExtra("post_actor_id", mCurrentId);
			startActivity(intent);
			break;
		default:
			break;
		}
	}
	
	private class PersonBeanTag implements ITag<PersonBean> {

		@Override
		public void refreshUI(PersonBean t, DataState ds) {
			mProgressDialog.dismiss();
			if (t != null) {
				fillData(t);
				pb= (PersonBean)t;
			} else {
				Toast.makeText(PersonCenterActivity.this, R.string.loaded_data_fail, Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			mProgressDialog.dismiss();
			if (!TextUtils.isEmpty(parseError.getErrMsg())) {
				return false;
			} else {
				Toast.makeText(PersonCenterActivity.this, R.string.loaded_data_fail, Toast.LENGTH_SHORT).show();
				return true;
			}
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	private class DialogueTag implements ITag<DialoguesMessageBean> {

		@Override
		public void refreshUI(DialoguesMessageBean t, DataState ds) {
			mProgressDialog.dismiss();
			if (t != null && t.getActor_dialogue()!= null) {
				ActorDialogueBean bean = t.getActor_dialogue();
				Intent intent = new Intent(PersonCenterActivity.this, ChatLetterActivity.class);
				intent.putExtra(KidAction.ACTOR_DIALOGUE_ID, String.valueOf(bean.getActor_dialogue_id()));
				intent.putExtra(KidAction.DIALOGUE_ID, String.valueOf(bean.getDialogue_id()));
				startActivity(intent);
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			mProgressDialog.dismiss();
			if (!TextUtils.isEmpty(parseError.getErrMsg())) {
				return false;
			} else {
				Toast.makeText(PersonCenterActivity.this, "会话连接失败!", Toast.LENGTH_SHORT).show();
				return true;
			}
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	private class AttentionTag implements ITag<StatuResult> {

		@Override
		public void refreshUI(StatuResult t, DataState ds) {
			mProgressDialog.dismiss();
			if (t != null && t.getResult()==0 && TextUtils.isEmpty(t.getDesc())) {
				Toast.makeText(PersonCenterActivity.this, "关注成功", 1).show();
				if (relation == UserBean.RELATION_NONE) {
					mImgAttention.setImageResource(R.drawable.icon_attention_ta);
				} else if (relation == UserBean.RELATION_FOLLOWING){
					mImgAttention.setImageResource(R.drawable.icon_attentioned);
				}
				if (relation == UserBean.RELATION_NONE) {
					relation = UserBean.RELATION_FOLLOWING;
				} else if (relation == UserBean.RELATION_FOLLOWING){
					relation = UserBean.RELATION_FRIENDS;
				}
			} else {
				Toast.makeText(PersonCenterActivity.this, "关注失败", 1).show();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			mProgressDialog.dismiss();
			if (!TextUtils.isEmpty(parseError.getErrMsg())) {
				return false;
			} else {
				Toast.makeText(PersonCenterActivity.this, "关注失败", 1).show();
				return true;
			}
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
		
	}
	
	private class DelAttenTag implements ITag<StatuResult> {

		@Override
		public void refreshUI(StatuResult t, DataState ds) {
			mProgressDialog.dismiss();
			if (t != null && t.getResult()==0  && TextUtils.isEmpty(t.getDesc())) {
				Toast.makeText(PersonCenterActivity.this, "取消关注成功", 1).show();
				if (relation == UserBean.RELATION_FRIENDS) {
					mImgAttention.setImageResource(R.drawable.icon_attention_me);
				} else if (relation == UserBean.RELATION_FOLLOWING) {
					mImgAttention.setImageResource(R.drawable.icon_attention);
				}
				if (relation == UserBean.RELATION_FRIENDS) {
					relation = UserBean.RELATION_FOLLOWED_BY;
				} else if (relation == UserBean.RELATION_FOLLOWING){
					relation = UserBean.RELATION_NONE;
				}
			} else {
				Toast.makeText(PersonCenterActivity.this, "取消关注失败", 1).show();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			mProgressDialog.dismiss();
			if (!TextUtils.isEmpty(parseError.getErrMsg())) {
				return false;
			} else {
				Toast.makeText(PersonCenterActivity.this, "取消关注失败", 1).show();
				return true;
			}
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
		
	}

}
